給定一個包含括號且只有加減法的運算式,回傳計算後的結果
basic calculator 總共有四個題組,這是第一個,因為需考慮到括號內的內容要先算,所以要考慮的事就變多了
初始化:
current
最後再把 current 與 output 結合即可
class Solution:
def calculate(self, s: str) -> int:
output, curr, sign, stack = 0,0,1,[]
for c in s:
# digit
if c.isdigit():
curr = curr*10 + int(c)
elif c == '-' or c == '+':
output += sign * curr
sign = -1 if c == '-' else 1
curr = 0
elif c == '(':
stack.append(output)
stack.append(sign)
output = 0
sign = 1
elif c == ')':
output += curr*sign
output *= stack.pop()
output += stack.pop()
curr = 0
else:
continue
return output + sign*curr